package com.huanzhidadi.rabbitmq.controller;

import com.huanzhidadi.rabbitmq.model.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
@Api(tags = "RabbitMQ测试")
@RestController
@RequestMapping("send")
public class RabbitMQSendController {

    @Autowired
    private AmqpTemplate amqpTemplate;

    @ApiOperation(value = "direct模式", notes = "direct模式")
    @RequestMapping(value = "/directPush", method = RequestMethod.GET)
    public void directPush() {
        amqpTemplate.convertAndSend("directPushMessage", "direct模式");
    }

    @ApiOperation(value = "direct模式Object", notes = "direct模式Object")
    @RequestMapping(value = "/directPushObject", method = RequestMethod.GET)
    public void directPushObject() {
        User user = new User();
        user.setId("1");
        user.setName("wang");
        user.setAge(33);
        amqpTemplate.convertAndSend("directPushObject", user);
    }

    @ApiOperation(value = "topicA", notes = "topicA")
    @RequestMapping(value = "/topicA", method = RequestMethod.GET)
    public void topic2A() {
        amqpTemplate.convertAndSend("topicExchange", "topic.a", "topic a");
    }

    @ApiOperation(value = "topic2", notes = "topic2")
    @RequestMapping(value = "/topic2", method = RequestMethod.GET)
    public void topic22() {
        amqpTemplate.convertAndSend("topicExchange", "topic.2", "topic 2");
    }

    @ApiOperation(value = "fanout", notes = "fanout")
    @RequestMapping(value = "/fanout", method = RequestMethod.GET)
    public void fanout() {
        // 注意第二个参数
        amqpTemplate.convertAndSend("fanoutExchange", "", "fanout message");
    }

    @ApiOperation(value = "delay", notes = "delay")
    @RequestMapping(value = "/delay", method = RequestMethod.GET)
    public void delay() {
        SimpleDateFormat dateFormat = new SimpleDateFormat(("yyyy-MM-dd HH:mm:ss"));
        log.info("消息发送时间：{}", dateFormat.format(new Date()));
        amqpTemplate.convertAndSend("delayed_exchange", "delay_routing_key", "delayed message", new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                // 消息延迟3s
                // message.getMessageProperties().setHeader("x-delay", 3000);
                message.getMessageProperties().setDelay(3000);
                return message;
            }
        });
    }
}
